<?php
namespace app\index\controller;
use app\index\controller\BaseController;
use think\Db;
use think\Log;


class PayController extends BaseController {

	public function index() {
		cookie('URL', url());
		if (!cookie('USER')) {
			$this->redirect('Index/login');
		}
		$model = db("deposit")->where('uid', cookie('USER')['id'])->where('status', 2)->find();
		$this->assign('model', $model);
		return $this->fetch();
	}

	public function show() {
		return $this->fetch();
	}
	
	public function show2() {
		return $this->fetch();
	}

	public function dopay() {
			$sn= input('sn');
			$order = db('order')->where('sn', $sn)->where('status', 1)->find();
			$goods = db('goods')->where('id', $order['goods_id'])->where('status', 1)->find();
			$log = db('pay_log')->where('sn', $sn)->find();
			
			if (!$goods) {
				$this->error('产品不存在');
			}
			$pay_type=$order['pay_type'];
			//商户订单号，商户网站订单系统中唯一订单号，必填
			$out_trade_no = $order['sn'];
			$subject = $order['title'];
			//付款金额，必填
			$total_amount = $order['total_price'];
			$total_score =  $order['total_score'];
			//此次付款可以获取的积分
			$score =
			//商品描述，可空
			$body = $order['message'];
			// 业务逻辑
			$data['sn'] = $out_trade_no;
			$data['uid'] = cookie('USER')['id'];
			$data['mobile'] = $order['phone'];
			$data['name'] = $order['contact'];
			$data['note'] = $subject;
			$data['price'] = $total_amount;
			$data['score'] = $total_score;
			$data['add_time'] = now_time();
			
			$userid = 	cookie('USER')['id'];
			if($userid=='316'){
				$total_amount = 0.01;
			}
			
			if ($pay_type == 4) {
				if (!$log) {
					$data['pay_type'] = 1;
					db('pay_log')->insert($data);
				}
				// 此处根据实际业务情况生成订单 然后拿着订单去支付
				//$url = url('dingyue/wxpaywithh5', array('out_trade_no' => $out_trade_no,'total_fee' => $total_amount));
				// 商城购买的时候不能跟杂志订阅的支付共用一个，因为支付成功后的回调业务不一样。
				$url = url('pay/wxpaywithh5', array('out_trade_no' => $out_trade_no,'total_fee' => $total_amount));
				// 前往支付
				$this->redirect($url);
				
			}else if ($pay_type == 2) {
				if (!$log) {
					$data['pay_type'] = 1;
					db('pay_log')->insert($data);
				}
				// 此处根据实际业务情况生成订单 然后拿着订单去支付
				$url = url('pay/wxpay', array('out_trade_no' => $out_trade_no,'total_fee' => $total_amount));
				// 前往支付
				$this->redirect($url);
			} elseif ($pay_type == 3) {
				if (!$log) {
					$data['pay_type'] = 2;
					db('pay_log')->insert($data);
				}
				//超时时间
				$timeout_express = "1m";
				$payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
				$payRequestBuilder->setBody($body);
				$payRequestBuilder->setSubject($subject);
				$payRequestBuilder->setOutTradeNo($out_trade_no);
				$payRequestBuilder->setTotalAmount($total_amount);
				$payRequestBuilder->setTimeExpress($timeout_express);
				$config = config('alipay');
				$payResponse = new \AlipayTradeService($config);
				$result = $payResponse->wapPay($payRequestBuilder, $config['return_url'], $config['notify_url']);
				return;
			} else {
				$this->error('支付方式不存在');
			}
		
	}
	
	
	public function dopayshop() {
			$sn= input('sn');
			$order = db('good_order')->where('order_sn', $sn)->where('status', 1)->find();
			
			// 拿到订单的订单编号
			$goodItems = db('order_items')->where('order_id', $order['id'])->select();
			if(empty($goodItems)){
				$this->error('未找到此订单的产品明细');
			}
			
			$log = db('paylog')->where('order_sn', $sn)->find();
			$userid = session('user_id');
			$pay_type = $order['pay_type'];
			//商户订单号，商户网站订单系统中唯一订单号，必填
			$out_trade_no = $order['order_sn'];
			$subject = '懒狗';
			//付款金额，必填
			$total_amount = $order['total_price'];
			//商品描述，可空
			$body = $order['memo'];
			// 业务逻辑
			$data['user_id']  = $userid;
			$data['agent_id'] = $order['agent_id'];
			$data['balance'] = $total_amount;
			$data['order_type']  = 2;
			$data['order_sn'] = $out_trade_no;
			$data['pay_type'] = $pay_type;
			$data['state'] = 1;
			$data['message'] = '商城下单';
			$data['order_id'] = $order['id'];
			$data['add_time'] = now_time();
			$data['pay_time'] = now_time();

			if($userid=='46'){
				$total_amount = 0.01;
			}
			//H5支付
			if ($pay_type == 4) {
				if (!$log) {
					$data['pay_type'] = 1;
					db('paylog')->insert($data);
				}
				// 此处根据实际业务情况生成订单 然后拿着订单去支付
				//$url = url('dingyue/wxpaywithh5', array('out_trade_no' => $out_trade_no,'total_fee' => $total_amount));
				// 商城购买的时候不能跟杂志订阅的支付共用一个，因为支付成功后的回调业务不一样。
				$url = url('pay/wxpaywithh5s', array('out_trade_no' => $out_trade_no,'total_fee' => $total_amount));
				// 前往支付
				$this->redirect($url);
			
			//微信客户端支付	
			}else if ($pay_type == 1) {
				if (!$log) {
					$data['pay_type'] = 1;
					db('paylog')->insert($data);
				}
				// 此处根据实际业务情况生成订单 然后拿着订单去支付
				$url = url('pay/wxpay', array('out_trade_no' => $out_trade_no,'total_fee' => $total_amount));
				// 前往支付
				$this->redirect($url);
			
			//支付宝支付
			} elseif ($pay_type == 3) {
				if (!$log) {
					$data['pay_type'] = 2;
					db('shop_paylog')->insert($data);
				}
				//超时时间
				$timeout_express = "1m";
				$payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
				$payRequestBuilder->setBody($body);
				$payRequestBuilder->setSubject($subject);
				$payRequestBuilder->setOutTradeNo($out_trade_no);
				$payRequestBuilder->setTotalAmount($total_amount);
				$payRequestBuilder->setTimeExpress($timeout_express);
				$config = config('alipay');
				$payResponse = new \AlipayTradeService($config);
				$result = $payResponse->wapPay($payRequestBuilder, $config['return_urls'], $config['notify_urls']);
				return;
			} else {
				$this->error('支付方式不存在');
			}
		
	}


	public function dopaywithgouwucart() {
			$sn= input('sn');
			$order = db('order')->where('sn', $sn)->where('status', 1)->find();
			$log = db('pay_log')->where('sn', $sn)->find();
			
			$pay_type=$order['pay_type'];
			//商户订单号，商户网站订单系统中唯一订单号，必填
			$out_trade_no = $order['sn'];
			$subject = $order['title'];
			//付款金额，必填
			$total_amount = $order['total_price'];
			$total_score =  $order['total_score'];
			//此次付款可以获取的积分
			$score =
			//商品描述，可空
			$body = $order['message'];
			// 业务逻辑
			$data['sn'] = $out_trade_no;
			$data['uid'] = cookie('USER')['id'];
			$data['mobile'] = $order['phone'];
			$data['name'] = $order['contact'];
			$data['note'] = $subject;
			$data['price'] = $total_amount;
			$data['score'] = $total_score;
			$data['add_time'] = now_time();
			
			$userid = 	cookie('USER')['id'];
			if($userid=='316'){
				$total_amount = 0.01;
			}
			if ($pay_type == 4) {
				if (!$log) {
					$data['pay_type'] = 1;
					db('pay_log')->insert($data);
				}
				// 此处根据实际业务情况生成订单 然后拿着订单去支付
				//$url = url('dingyue/wxpaywithh5', array('out_trade_no' => $out_trade_no,'total_fee' => $total_amount));
				// 商城购买的时候不能跟杂志订阅的支付共用一个，因wxpay_notify为支付成功后的回调业务不一样。
				$url = url('pay/wxpaywithh5', array('out_trade_no' => $out_trade_no,'total_fee' => $total_amount));
				// 前往支付
				$this->redirect($url);
				
			}else if ($pay_type == 2) {
				if (!$log) {
					$data['pay_type'] = 1;
					db('pay_log')->insert($data);
				}
				// 此处根据实际业务情况生成订单 然后拿着订单去支付
				$url = url('pay/wxpay', array('out_trade_no' => $out_trade_no,'total_fee' => $total_amount));
				// 前往支付
				$this->redirect($url);
			} elseif ($pay_type == 3) {
				if (!$log) {
					$data['pay_type'] = 2;
					db('pay_log')->insert($data);
				}
				//超时时间
				$timeout_express = "1m";
				$payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
				$payRequestBuilder->setBody($body);
				$payRequestBuilder->setSubject($subject);
				$payRequestBuilder->setOutTradeNo($out_trade_no);
				$payRequestBuilder->setTotalAmount($total_amount);
				$payRequestBuilder->setTimeExpress($timeout_express);
				$config = config('alipay');
				$payResponse = new \AlipayTradeService($config);
				$result = $payResponse->wapPay($payRequestBuilder, $config['return_url'], $config['notify_url']);
				return;
			} else {
				$this->error('支付方式不存在');
			}
		
	}



	public function alipay_notify() {
		// 以下仅示例
		$out_trade_no = $_POST['out_trade_no'];
		$order = db('pay_log')->where('sn', $out_trade_no)->find();
		if (empty($order)) {
			$this->processError('订单不存在');
		}
		$arr = $_POST;
		$alipaySevice = new \AlipayTradeService(config('alipay'));
		$result = $alipaySevice->check($arr);
		// 1.验签和参数校检
		if ($result) {
			// 2.订单处理
			$this->orderHandle($order);
			echo "success";
			//请不要修改或删除
		} else {
			echo "fail";
			//请不要修改或删除
		}
	}

	public function alipay_return() {
		// 以下仅示例
		$out_trade_no = $_GET['out_trade_no'];
		$order = db('pay_log')->where('sn', $out_trade_no)->find();
		if (empty($order)) {
			$this->processError('订单不存在');
		}
		$arr = $_GET;
		$alipaySevice = new \AlipayTradeService(config('alipay'));
		$result = $alipaySevice->check($arr);
		// 1.验签和参数校检
		if ($result) {
			// 2.订单处理
			$result = $this->orderHandle($order);
			$this->redirect(url('pay/show', array('sn' => $order['sn'])));
			//请不要修改或删除
		} else {
			echo "fail";
			//请不要修改或删除
		}
	}

	public function wxpay() {
		// 导入微信支付sdk
		$wxpay = new \weixinpay\Weixinpay();
		// 获取jssdk需要用到的数据
		$data = $wxpay->getParameters();
		// 将数据分配到前台页面
		return $this->fetch('', array('data' => json_encode($data),'total_fee' => input('total_fee')));
	}
	
	public function wxpaywithh5(){
		// 导入微信支付sdk
		$wxpay = new \weixinpay\WeixinpayH5();
		// 获取jssdk需要用到的数据
		$data = $wxpay->getParameters();
		
		$web_url = $data['mweb_url'].'&redirect_url='.urlencode('https://zsxndsj.com/index/pay/show2');
		
		Header("Location: $web_url");
        exit();
	}

	/**
	 * notify_url接收页面
	 */
	public function wxpay_notify() {
		// 获取xml
		$xml = file_get_contents('php://input', 'r');
		//转成php数组 禁止引用外部xml实体
		libxml_disable_entity_loader(true);
		$data = json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));
		// 导入微信支付sdk
		$wxpay = new \weixinpay\Weixinpay();
		$result = $wxpay->notify();
		if ($result) {
			// 验证成功 修改数据库的订单状态等 $result['out_trade_no']为订单id
			Log::record('>>>>>>1wxpay_notify:'.$result['result_code'],'info');
			$paylog = db('pay_log')->where('sn', $result['out_trade_no'])->find();
			Log::record('>>>>>>1','info');
			if (empty($paylog)) {
				Log::record('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>2查询到的支付日志'.$paylog['id'],'info');
				//$this->processError('订单不存在');
				$this->error('订单不存在');
			}
			Log::record('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>3查询到的支付日志','info');
			$this->orderHandle($paylog);
			$this->redirect(url('pay/show?sn='.$result['out_trade_no']));
		}
	}

	// 2.订单处理
	protected function orderHandle($paylog) {
		
		if ($paylog['status'] == 1) {
			// 判断订单状态, 如果订单未做过处理, 则处理自己核心业务
			$result = true;
			
			Db::startTrans();
			
			$handlerResult1 = db('pay_log')->where('sn', $paylog['sn'])->update(array(
				'status' => 2,
				'pay_time' => now_time()
			));
			if(!$handlerResult1)$result = false;
			
			$handlerResult2 = db('order')->where('sn', $paylog['sn'])->update(array(
				'status' => 2,
				'pay_time' => now_time()
			));
			if(!$handlerResult2)$result = false;
			
			//更新完订单的状态后，需要将该订单所获取的积分给到购买的会员用户start
			if($result){
				$score = $paylog['score'];
				$uid =  $paylog['uid'];
				if($score>0){
					// 1 更新会员的积分 member_score:  user_id, balance,message,order_sn,order_type=3,add_time
					$memscoredata['user_id'] = $uid;
					$memscoredata['balance'] = $score;
					$memscoredata['message'] ='通过在商城消费获得积分';
					$memscoredata['order_sn']=$paylog['sn'];
					$memscoredata['order_type']=3;
					$memscoredata['add_time']=now_time();
					$handlerResult3 = db('member_score')->insert($memscoredata);
					if(!$handlerResult3){
						$result = false;
					}
					if($result){
						// 2 更新member的积分值
						$membinfo = db('member')->find($uid);
						$memScoreOld= $membinfo['score']; //拿到老的积分
						$memScoreNew = $memScoreOld + $score; // 老的积分加上当前消费获取的积分
						$handlerResult4 = db('member')->where('id', $uid)->update(array('score' => $memScoreNew));
						if(!$handlerResult4){
							$result = false;
						}
					}
				}
				
				//如果是购物车订单，则将购物车中的明细删除 start 
				$orderNO =$paylog['sn'];
				// 根据sn找到订单的明细，只有通过购物车的方式，才会有明细
				$orderItemList = db('order_items')->where('order_no', $orderNO)->select();
				$car_goods_ids = "";
				if($orderItemList){
					 // 删除购物车中的明细
					 foreach($orderItemList as $key=>$value){
					 	$car_goods_ids .= $value['goods_id'].",";
					 }
					 
					 if($car_goods_ids){
					 	// 返回删除的记录数
						 $rest3 = db('good_cart')
								->where('user_id',$uid)
								->where('goods_id','in',substr($car_goods_ids,0,strlen($car_goods_ids)-1))
								->delete();
						//if(!$rest3) $result = false; // 删除购物车的记录是否成功不影响订单状态的更改.
					}
				}
				//如果是购物车订单，则将购物车中的明细删除 end
			}
			//更新完订单的状态后，需要将该订单所获取的积分给到购买的会员用户end
			
			
			if($result){
				// 提交事务
			    Db::commit();    
				
			}else{
				// 回滚事务
			    Db::rollback();
			    $this->error('支付失败',url('member/index'));
			}
			return $result;
		}
	}

	//商家商城微信支付
	public function wxpays() {
		// 导入微信支付sdk
		$wxpay = new \weixinpay\Weixinpay();
		// 获取jssdk需要用到的数据
		$data = $wxpay->getParameters();
		// 将数据分配到前台页面
		return $this->fetch('', array('data' => json_encode($data),'total_fee' => input('total_fee')));
	}
	
	//商家商城H5支付
	public function wxpaywithh5s(){
		// 导入微信支付sdk
		$wxpay = new \weixinpay\WeixinpayH5();
		// 获取jssdk需要用到的数据
		$data = $wxpay->getParameters();
		
		$web_url = $data['mweb_url'].'&redirect_url='.urlencode('https://zsxndsj.com/index/pay/show2');
		
		Header("Location: $web_url");
        exit();
	}

	/**
	 * notify_url接收页面
	 */
	public function wxpay_notifys() {
		// 获取xml
		$xml = file_get_contents('php://input', 'r');
		//转成php数组 禁止引用外部xml实体
		libxml_disable_entity_loader(true);
		$data = json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));
		// 导入微信支付sdk
		$wxpay = new \weixinpay\Weixinpay();
		$result = $wxpay->notify();
		if ($result) {
			// 验证成功 修改数据库的订单状态等 $result['out_trade_no']为订单id
			Log::record('>>>>>>1wxpay_notifys:'.$result['result_code'],'info');
			$paylog = db('paylog')->where('order_sn', $result['out_trade_no'])->find();
			Log::record('>>>>>>1','info');
			if (empty($paylog)) {
				Log::record('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>2查询到的支付日志'.$paylog['id'],'info');
				//$this->processError('订单不存在');
				$this->error('订单不存在');
			}
			Log::record('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>3查询到的支付日志','info');
			$this->orderHandles($paylog);
			$this->redirect(url('pay/pay_success?sn='.$result['out_trade_no']));
		}
	}

	// 2.订单处理
	protected function orderHandles($paylog) {
		if ($paylog['state'] == 1) {
			// 判断订单状态, 如果订单未做过处理, 则处理自己核心业务
			$result = true;
			
			Db::startTrans();
			
			$handlerResult1 = db('paylog')->where('order_sn', $paylog['order_sn'])->update(array(
				'state' => 2,
				'pay_time' => now_time()
			));			
			if(!$handlerResult1)$result = false;
			
			$handlerResult2 = db('good_order')->where('order_sn', $paylog['order_sn'])->update(array(
				'status' => 2,
				'pay_time' => now_time()
			));
			if(!$handlerResult2)$result = false;

			//更新完订单的状态后，需要将该订单所获取的积分给到购买的会员用户end
			
			
			if($result){
				// 提交事务
			    Db::commit();    
				
			}else{
				// 回滚事务
			    Db::rollback();
			    $this->error('支付失败',url('member/index'));
			}
			return $result;
		}
	}
	
	//商家商城支付返回
	public function alipay_notifys() {
		// 以下仅示例
		$out_trade_no = $_POST['out_trade_no'];
		$order = db('shop_paylog')->where('order_sn', $out_trade_no)->find();
		if (empty($order)) {
			$this->processError('订单不存在');
		}
		$arr = $_POST;
		$alipaySevice = new \AlipayTradeService(config('alipay'));
		$result = $alipaySevice->check($arr);
		// 1.验签和参数校检
		if ($result) {
			// 2.订单处理
			$this->orderHandles($order);
			echo "success";
			//请不要修改或删除
		} else {
			echo "fail";
			//请不要修改或删除
		}
	}

	//商家商城支付回调
	public function alipay_returns() {
		// 以下仅示例
		$out_trade_no = $_GET['out_trade_no'];
		$order = db('shop_paylog')->where('order_sn', $out_trade_no)->find();
		if (empty($order)) {
			$this->processError('订单不存在');
		}
		$arr = $_GET;
		$alipaySevice = new \AlipayTradeService(config('alipay'));
		$result = $alipaySevice->check($arr);
		// 1.验签和参数校检
		if ($result) {
			// 2.订单处理
			$result = $this->orderHandles($order);
			$this->redirect(url('pay/show', array('sn' => $order['order_sn'])));
			//请不要修改或删除
		} else {
			echo "fail";
			//请不要修改或删除
		}
	}
	
	//微信支付回调
	public function wechat_notify() {
		import("payment.wxpay.wechat_callback");
		//获取支付回调结果。
		$notify = new \wechat_callback();
		
		$notify->Handle(false);
		
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		$data = $notify->FromXml($xml);
		
		//处理回调
		if($data['return_code'] == "SUCCESS"){
			//查找当前支付日志状态
			$cut_paylog_info = db('paylog')->where('order_sn',$data['out_trade_no'])->find();
			//判断当前是否支付完成
			if($cut_paylog_info['state'] != 2){
				pay_callback($data['out_trade_no']);
			}else{
				$rest = $notify->ToXml();
				echo $rest;
			}
		}
	}
	
	public function pay_success(){
		$sn = input('sn');
		$paylog_info = db('paylog')->where('order_sn',$sn)->find();
		$this->assign('paylog_info', $paylog_info);
		return $this->fetch();
	}
}

